﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public enum NetStatus
{
    Connected,
    Connecting,
    Disconnect,
}

/// <summary>
/// Socket连接
/// </summary>
public class TCPRemote: Remote,ITCPSocketServer
{
    protected long m_DisconnectTime;
    public long disconnectTime => m_DisconnectTime;
    
    public /*override*/ bool connected => m_SocketServer != null && m_SocketServer.connected;

    //每个TCPRemote都有一个Socket连接
    TCPSocketServer TCPSocketServer => m_SocketServer as TCPSocketServer;

    Action<TCPRemote> m_OnDisconnect;


    public TCPRemote(TCPSocketServer _server, Action<TCPRemote> onDisconnect) : base(0, _server.ipEndPoint, _server)
    {
        Init(_server, onDisconnect);
    }

    public TCPRemote(long clientId, TCPSocketServer _server,Action<TCPRemote> onDisconnect) : base(clientId,_server.ipEndPoint, _server)
    {
        Init(_server, onDisconnect);
    }

    void Init(TCPSocketServer _server, Action<TCPRemote> onDisconnect)
    {
        m_OnDisconnect = onDisconnect;

        _server.tcpServerListener = this;

        BeginReceive();
    }

    /// <summary>
    /// 异步接收
    /// </summary>
    public void BeginReceive()
    {
        TCPSocketServer.BeginReceive();

        m_DisconnectTime = 0;
    }


    void ITCPSocketServer.OnNewConnected(EndPoint endPoint, Socket connect)
    {
        //GameDebug.Log($"连接上：{endPoint}");
    }

    public virtual void OnReceiveData(EndPoint endPoint, byte[] data)
    {
        OnProcessMessageData(data);
    }


    public virtual void OnRecOrSendFailed(EndPoint endPoint)
    {
        GameDebug.Log($"用户断线 :{this.ipEndPoint}");

        m_DisconnectTime = (long)(System.DateTime.Now.Ticks / 10000000d);
        try
        {
            m_OnDisconnect?.Invoke(this);
        }
        catch(Exception e)
        {
            GameDebug.LogError(e.Message + "\n" + e.StackTrace);
        }
    }


    public override string ToString()
    {
        return $"TCPRemote: {this.ipEndPoint} Address:{this.ipEndPoint.Address}  connected:{this.connected}";
    }

}

